<template>
    <div class="navigation-page">
        <div class="clearfix">
            <el-button class="float-right ml30" type="primary" link @click="resetNav(dynamicForm)">恢复初始导航</el-button>
            <el-button class="float-right" type="primary" link @click="handleNav('add')" :icon="Plus">添加一级导航</el-button>
        </div>
        <div class="mt20">
            <el-form ref="dynamicForm" :model="config" v-if="loading" class="nav-form">
                <ul class="navigation-ul">
                    <draggable :animation="500"
                    ghost-class="ghost"
                    handle=".header-icon"
                    :list="config.navigations"
                    :move="checkMove">
                    <li v-for="(item, index) in config.navigations" :key="item.id" :name="item.id" :class="{'noSubNav': item.sub_navs && !item.sub_navs.length}">
                        <div class="collapse-header" @click.stop>
                            <el-form-item label="" style="width: 36px">
                                <el-icon v-if="item.moduleKey!=='home'" class="header-icon"><Operation /></el-icon>
                            </el-form-item>
                            <el-form-item class="w100 ml20" label="">
                                {{item.name}}
                            </el-form-item>
                            <!-- 初始化导航 -->
                            <el-form-item class="ml20" v-show="item.type == 1" label="自定义名称:">
                                <el-input v-model="item.custom_name" placeholder="请输入自定义名称" maxlength="10" show-word-limit />
                            </el-form-item>
                            <!-- 自定义一级导航 -->
                            <el-form-item class="ml20" v-if="item.type == 2"  :prop="'navigations.' + index + '.custom_name'" :rules="navRule">
                                <el-input v-model="item.custom_name" placeholder="请输入导航名称" maxlength="10" show-word-limit />
                            </el-form-item>
                            <el-form-item class="ml20" v-if="item.moduleKey!=='home'&&!item.sub_navs.length" label="" :prop="'navigations.' + index + '.link'" :rules="navLinkRule">
                                <el-input class="link-input" v-model="item.link" placeholder="https://www.3ren.cn/wisdom/index" readonly>
                                    <template #suffix>
                                        <el-button type="primary" link @click.stop="handleSubNavLink('add', item, index)">{{item.link ? '编辑链接/应用' : '添加链接/应用' }}</el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item v-if="item.moduleKey!=='home'" class="ml20">
                                <el-button type="primary" @click="addSubNav(item)">添加下级导航</el-button>
                                <el-button v-show="index" type="primary" @click="handleNav('delete', index)">删除</el-button>
                            </el-form-item>

                            <i class="iconfont nav-icon" v-if="item.sub_navs && item.sub_navs.length" :class="[item.open ? 'icon-wandzhankaishouqi' : 'icon-wanda-youxiao']" @click.stop="item.open = !item.open"></i>
                        </div>
                        <ul class="sub-nav-list" v-show="item.sub_navs && item.sub_navs.length && item.open">
                            <li class="sub-nav-item" v-for="(sub_nav, $index) in item.sub_navs" :key="sub_nav.id">
                                <div class="subnav-item-index">{{$index+1}}</div>
                                <div class="subnav-item-content">
                                    <el-form-item class="subnav-item-name" label="导航名称:" :prop="'navigations.' + index + '.sub_navs.' + $index + '.name'" :rules="navRule">
                                        <el-input v-model="sub_nav.name" placeholder="请输入导航名称" maxlength="10" show-word-limit />
                                    </el-form-item>
                                    <el-form-item class="subnav-item-name ml20" :prop="'navigations.' + index + '.sub_navs.' + $index + '.link'" :rules="subNavLinkRule">
                                        <div class="link-box">
                                            <div class="application-box text-overflow">{{showName(sub_nav)}}</div>
                                            <el-button class="operate-link-btn" type="primary" link @click="handleSubNavLink('add', sub_nav, $index, index)">{{ sub_nav.link ? '添加链接/应用' : '编辑链接/应用' }}</el-button>
                                        </div>
                                    </el-form-item>
                                </div>
                                <div class="nav-item-operate">
                                    <el-button type="primary" link @click="delSubNav(item, $index)">删除</el-button>
                                    <el-button type="primary" v-show="$index" link @click="move(item, $index, 'up')">上移</el-button>
                                    <el-button type="primary" v-show="$index > -1 && $index !== item.sub_navs.length - 1" link @click="move(item, $index, 'down')">下移</el-button>
                                </div>
                            </li>
                        </ul>
                    </li>
                </draggable>
                </ul>
            </el-form>
            
            <div class="footer-save-btn">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="save(dynamicForm)" v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
            </div>
        </div>
        <!-- <AddNaviagtion
            v-if="addNavDialog.show"
            v-model:show="addNavDialog.show"
            :title="addNavDialog.title"
            :edit-status="addNavDialog.editStatus"
            @update:confirm="addNav">
        </AddNaviagtion> -->

        <!-- 添加应用/链接 -->
        <AddLink
            v-if="addSubNavDialog.show"
            v-model:show="addSubNavDialog.show"
            :linkInfo="currentSubLink"
            :title="addSubNavDialog.title"
            :edit-status="addSubNavDialog.editStatus"
            @update:confirm="addLinkConfirm">
        </AddLink>
    </div>
</template>

<script setup>
// import AddNaviagtion from './add-navigation.vue'
import AddLink from './add-link.vue';
import { ElCollapse, ElCollapseItem, ElCollapseTransition } from 'element-plus'
import { Plus, Search, Operation } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, defineProps, watch, nextTick } from 'vue'
import { useStore } from 'vuex';
import { useRoute } from 'vue-router'
import { VueDraggableNext as draggable } from 'vue-draggable-next'
import Fn from '@/lib/fn.js';
import { navigationList } from '../../filter-data.js'
import { deepCopy } from '@/lib/tools.js'
import { pageJump } from '@/global/location-transfer';

const store = useStore();
const route = useRoute();

const props = defineProps({
    currentTab: { // 当前tab
        type: String,
        default: 'navigation'
    }
});

// form表单
const dynamicForm = ref();

const config = reactive({
    id: null,
    navigations: []
})

const loading = ref(true);

const fullscreenLoading = ref(false);

const handleChange = (data) => {
    console.log('data', data)
}

const validateNav = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入导航名称'))
    } else {
        callback()
    }
}


const validateSubNavLink = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请添加链接/应用'))
    } else {
        callback()
    }
}
const navRule = reactive({
    validator: validateNav,
    trigger: 'blur'
})

const navLinkRule = reactive({
    required: true,
    validator: validateSubNavLink,
    trigger: 'blur'
})

const subNavLinkRule = reactive({
    required: true,
    validator: validateSubNavLink,
    trigger: 'change'
})

const navItem = {
    type: 2,
    name: '',
    custom_name: '',
    sub_navs: []
}

// // 新增编辑一级导航弹窗显隐
// const addNavDialog = reactive({
//     show: false,
//     editStatus: 'add',
//     title: '添加一级导航'
// });

// 添加一级导航
const addNav = () => {
    if(config.navigations.length>=10) {
        store.dispatch('message', {
            message: '最多只能添加10个一级导航'
        })
        return
    }
    config.navigations.push({
        id: Date.now(),
        type: 2,
        name: '一级导航名称：',
        custom_name: '',
        link: null,
        sub_navs: []
    })
}

const addSubNav = (item) => {
    delete item.link;
    delete item.moduleKey;

    if(item.sub_navs.length>=10) {
        store.dispatch('message', {
            message: '最多只能添加10个二级导航'
        })
        return
    }
    item.link = '';
    item.moduleKey = '';
    item.open = true;
   
    item.sub_navs.push({
        id: Date.now(),
        name: '',
        link_type: null,
        link: ''
    })
}
const delSubNav = (item, index) => {
    item.sub_navs.splice(index, 1)
}
const move = (item, index, type) => {
    switch (type) {
        case 'up':
            item.sub_navs[index] = item.sub_navs.splice(index - 1, 1, item.sub_navs[index])[0];
            break
        case 'down':
            item.sub_navs[index] = item.sub_navs.splice(index + 1, 1, item.sub_navs[index])[0];
            break
    }
    
}

const checkMove = (evt) => {
    return (evt.draggedContext.element.moduleKey!=='home'&&evt.relatedContext.element.moduleKey!=='home');
}

// 新增编辑二级导航弹窗显隐
const addSubNavDialog = reactive({
    show: false,
    editStatus: 'add',
    title: '添加链接'
});

// 获取站点导航配置
function getSiteConfig () {
    store.dispatch('proxyAction', {
        name: 'getTemplateConfig',
        queries: {
            institutionId: route.query.id, // 当前组织id
            componentType: 'navigation'
        }
    }).then((res) => {
        dynamicForm.value.resetFields();
        if(res.data) {
            config.navigations = JSON.parse(res.data.data);
            config.id = res.data.id;
        } else {
            config.navigations = deepCopy(navigationList)
        }
        config.navigations.forEach((item) => {
            item.open = false;
        })
    })
}

// 处理一级导航
function handleNav (type, index) {
    switch(type) {
        case 'add':
        case 'edit':
            addNav();
            break
        case 'delete':
            Fn.Confirm(function(){
                config.navigations.splice(index, 1)
            }, '确认要删除当前一级导航吗？', '确认删除')();
            break

    }
}
const currentSubLink = ref();


/**
 * 处理导航链接/应用
 * index：节点索引
 * parentIndex: 父节点索引
 */
function handleSubNavLink (type, info, index, parentIndex = -1) {

    currentSubLink.value = info;
    currentSubLink.value.index = index;
    currentSubLink.value.parentIndex = parentIndex;

    switch(type) {
        case 'add':
        case 'edit':
            addSubNavDialog.editStatus = type;
            addSubNavDialog.title = type === 'add' ? '添加链接/应用' : '编辑链接/应用';
            addSubNavDialog.show = true;
            break
        case 'delete':
            Fn.Confirm(function(){
            }, '确认要删除这个应用吗？', '确认删除')();
            break

    }
}


const addLinkConfirm = (data) => {
    console.log('data', data)
    currentSubLink.value = {};
    let index = data.index;
    let parentIndex = data.parentIndex;
    delete data.index;
    delete data.parentIndex;
    if(parentIndex === -1) { // 一级导航
        config.navigations[index] = deepCopy(data);
        dynamicForm.value.validateField('navigations.' + index + '.link', (valid) => {
            console.log('valid1', valid)
        });
    }else { // 二级导航
        config.navigations[parentIndex].sub_navs[index] = deepCopy(data);
        dynamicForm.value.validateField('navigations.' + parentIndex + '.sub_navs.' + index + '.link', (valid) => {
            console.log('valid', valid)
        });
    }
}

// 显示添加的链接或者应用
const showName = (info) => {
    if(info.link) {
        return info.link;
    }
    return '未添加链接/应用';
}

// 恢复初始导航 deepCopy(navigationList)
const resetNav = (formEl) => {
    Fn.Confirm(function(){
        console.log('aaa', deepCopy(navigationList))
        config.navigations = deepCopy(navigationList)
        console.log('navigations', config.navigations)
        loading.value = false
        nextTick(() => {
            loading.value = true
            formEl.resetFields()
        })
    }, '如果点击确认您当前编辑的信息将丢失。您确认要初始化到默认导航吗？', '确认恢复初始导航')();
}
const saveConfig = () => {
    fullscreenLoading.value = true
    store.dispatch('proxyAction', {
        name: 'saveSiteConfig',
        data: {
            client: 'pc',
            institutionId: route.query.id, // 当前组织id
            componentType: 'navigation',
            id: config.id,
            data: JSON.stringify(config.navigations)
        }
    }).then((res) => {
        config.id = res.data
        store.dispatch('message', {
            message: '站点导航配置成功'
        })
    }).finally(() => {
        fullscreenLoading.value = false
    })
}

const save = (formEl) => {
    formEl.validate((valid, fields) => {
        if (valid) {
            saveConfig()
        } else {
            config.navigations.forEach(item => {
                item.open = true;
            })
            store.dispatch('message', {
               message: '请检查必填项'
            })
        }
    })
}


const cancel = () => {
    pageJump({ name: 'siteList' });
}


// 初始化数据
onMounted(() => {
    // getSiteConfig()
})

// 监听外部tab改变，重置数据
watch(() => props.currentTab, (newVal) => {
    if (newVal === 'navigation') {
        getSiteConfig();
    }
})

</script>

<style lang="scss" scoped>
.w100 {
    width: 100px;
}
.el-input.link-input {
    width: 400px;
}
.ml20 {
    margin-left: 20px;
}
.ml30 {
    margin-left: 30px;
}
.collapse-header {
    width: 100%;
    height: 100%;
    display: flex;
    .el-form-item {
        align-items: center;
    }
}
.header-icon {
    margin-left: 12px;
    font-size: 24px;
    cursor: move;
}
.sub-nav-list {
    padding: 0;
    border: 1px solid #ddd;
    margin-bottom: 12px;
    .sub-nav-item {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ddd;
        .subnav-item-index {
            width: 50px;
            text-align: center;
        }
        .subnav-item-content {
            min-height: 60px;
            flex: 1;
            display: flex;
            align-items: center;
            border-left: 1px solid #ddd;
            border-right: 1px solid #ddd;
            padding: 0 16px;
            .subnav-item-name {
                flex: 1;
            }
            .link-box {
                flex: 1;
                position: relative;
            }
        }
    }
    .sub-nav-item:last-child {
        border-bottom: none;
    }
    .nav-item-operate {
        width: 150px;
        text-align: center;
    }
}
.empty-link {
    // width: 100%;
    height: 32px;
    border: var(--el-border);
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 0 80px 0 12px;
    line-height: 32px;
    color: #999;
}
.application-box {
    // width: 100%;
    height: 32px;
    border: var(--el-border);
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 0 12px;
    line-height: 32px;
}
.operate-link-btn {
    position: absolute;
    top: 8px;
    right: 12px;
}
.noSubNav :deep(.el-collapse-item__arrow) {
    display: none;
}
.el-form-item {
    margin-bottom: 0;
}

.mt20 {
    margin-top: 20px;
}
.footer-save-btn {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #eeeeee;
}
.nav-form {
    height: calc(100vh - 336px);
    overflow-y: auto;
    box-sizing: border-box;
    padding-bottom: 30px;
}
.navigation-ul {
    list-style: none;
    padding: 0px;
    margin: 0px;
    .collapse-header {
        position: relative;
        padding: 10px 0px;
        margin-bottom: 12px;
        border-radius: 4px;
        background: #f6f6f6;
    }
    .nav-icon {
        position: absolute;
        right: 20px;
        top: 18px;
        cursor: pointer;
    }
    
}
</style>